#include "dcmimagecache.h"
#include "imageinstance.h"
#include <QMutexLocker>

#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcdeftag.h"

DcmImageCache* DcmImageCache::inst = 0;
QMutex *DcmImageCache::m = new QMutex;

DcmImageCache& DcmImageCache::getCacher()
{
    if (!inst) {
        QMutexLocker l(m);
        if (!inst) {
            inst = new DcmImageCache;
        }
    }
    return *inst;
}

ImageInstance *DcmImageCache::getImage(const QString &key)
{
    QString _key = key;
    _key = _key.replace("/", "\\");
    ImageInstance *i = cache.object(_key);
    if (!i) {
        i = new ImageInstance(_key);
        if (i->isNormal()) {
            doInsertImage(i);
        } else {
            delete i;
            i = 0;
        }
    }
    return i;
}

void DcmImageCache::insertImage(ImageInstance *image)
{
    if (image && (!image->getImageFile().isEmpty()))
        doInsertImage(image);
}

void DcmImageCache::doInsertImage(ImageInstance *image)
{
    ulong w = 0, h = 0;
    image->getImageSize(w, h);
    bool ok;
    ulong bits = image->getTagKeyValue(DCM_BitsAllocated).toUInt(&ok);
    ulong bytes = (ok?bits:16) / 8;
    ulong cost = (w * h * bytes * 2 / (1024 * 1024));
    QString _key = image->getImageFile();
    _key = _key.replace("/", "\\");
    cache.insert(_key, image, cost);
}
